{- This file is part of funbot.
 -
 - Written in 2015, 2016 by fr33domlover <fr33domlover@riseup.net>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

{-# LANGUAGE OverloadedStrings #-}

-- | Show-history command
--
-- Show channel history
module FunBot.Commands.History
    ( cmdShowHistory
    )
where

import Control.Monad (unless, when)
import Data.List (find, intercalate)
import Data.Monoid ((<>))
import Data.Settings.Types (showOption)
import Data.Text (Text)
import FunBot.History (quote, reportHistory')
import FunBot.Memos (submitMemo)
import FunBot.Settings
import FunBot.Settings.Sections.Channels (addChannel)
import FunBot.Settings.Sections.Feeds (addFeed, deleteFeed)
import FunBot.Settings.Sections.Repos
import FunBot.Settings.Sections.Shortcuts (addShortcut, deleteShortcut)
import FunBot.Types
import FunBot.UserOptions
import FunBot.Util (getHistoryLines, cmds, helps)
import Network.IRC.Fun.Bot.Behavior
import Network.IRC.Fun.Bot.Chat
import Network.IRC.Fun.Bot.State
import Network.IRC.Fun.Bot.Types
import Text.Read (readMaybe)
import Network.IRC.Fun.Types.Base

import qualified Data.CaseInsensitive as CI
import qualified Data.Text as T
import qualified Data.Text.Read as TR

respondShowHistory
    :: Maybe Channel
    -> Nickname
    -> [Text]
    -> (MsgContent -> BotSession ())
    -> BotSession ()
respondShowHistory (Just chan) nick [mins] _send =
    case TR.decimal mins of
        Right (m, "") -> reportHistory' nick chan m
        _ -> failToChannel chan nick $ InvalidArg (Just 1) (Just mins)
respondShowHistory mchan nick [mins, chan] _send =
    case TR.decimal mins of
        Right (m, "") -> reportHistory' nick (Channel chan) m
        _ -> failBack mchan nick $ InvalidArg (Just 1) (Just mins)
respondShowHistory mchan nick args _send =
    failBack mchan nick $ WrongNumArgsN (Just $ length args) Nothing

cmdShowHistory = Command
    { cmdNames    = cmds ["show-history"]
    , cmdRespond  = respondShowHistory
    , cmdHelp     = helps
        [ ( "show-history <mins>"
          , "receive (privately) the channel history log for the last <mins> \
            \minutes, for the channel in which the command is used. The \
            \result may contain less than <mins> minutes because it also \
            \depends on the number of messages the bot remembers."
          )
        , ( "show-history <mins> <channel>"
          , "the same, for the specified channel. Use this variant in a \
            \private message to the bot."
          )
        ]
    , cmdExamples =
        [ "show-history 5"
        , "show-history 5 #freepost"
        ]
    }
